import {
	Client
} from '@stomp/stompjs';
import SockJS from 'sockjs-client';

// 连接状态枚举
const ConnectionState = {
	CONNECTING: 'CONNECTING',
	CONNECTED: 'CONNECTED',
	DISCONNECTED: 'DISCONNECTED',
	ERROR: 'ERROR'
};

let stompClient = null;
let subscriptions = {};
let connectionState = ConnectionState.DISCONNECTED;
let connectionListeners = [];

export default {
	// 初始化连接
	init(url, connectCallback, errorCallback, options = {}) {
		const {
			debug = true
		} = options;
		
		if (stompClient && this.isConnected()) {
			console.warn('STOMP客户端已连接，无需重复初始化');
			return;
		}

		// 默认配置
		const defaultOptions = {
			reconnectDelay: 5000,
			heartbeatIncoming: 4000,
			heartbeatOutgoing: 4000,
			debug: false,
			headers: {}
		};

		const config = {
			...defaultOptions,
			...options
		};

		this.updateConnectionState(ConnectionState.CONNECTING);
		console.log('正在建立STOMP连接...', {
			url,
			config
		});

		const socket = new SockJS(url);
		stompClient = new Client({
			webSocketFactory: () => socket,
			reconnectDelay: config.reconnectDelay,
			heartbeatIncoming: config.heartbeatIncoming,
			heartbeatOutgoing: config.heartbeatOutgoing,
			debug: function(str) {
				if (config.debug) {
					console.debug('STOMP调试:', str);
				}
			},
			connectHeaders: config.headers
		});

		stompClient.onConnect = (frame) => {
			console.log('STOMP连接成功', frame);
			this.updateConnectionState(ConnectionState.CONNECTED);
			connectCallback && connectCallback(frame);
			this.notifyConnectionListeners();
		};

		stompClient.onStompError = (frame) => {
			console.error('STOMP协议错误', frame);
			this.updateConnectionState(ConnectionState.ERROR);
			errorCallback && errorCallback(frame);
			this.notifyConnectionListeners();
		};

		stompClient.onWebSocketError = (error) => {
			console.error('WebSocket错误', error);
			this.updateConnectionState(ConnectionState.ERROR);
			errorCallback && errorCallback(error);
			this.notifyConnectionListeners();
		};

		stompClient.onDisconnect = (frame) => {
			console.log('STOMP连接断开', frame);
			this.updateConnectionState(ConnectionState.DISCONNECTED);
			this.notifyConnectionListeners();
		};

		stompClient.activate();
	},

	// 添加连接状态监听器
	addConnectionListener(listener) {
		if (typeof listener !== 'function') {
			console.error('连接监听器必须是一个函数');
			return;
		}
		connectionListeners.push(listener);
		// 立即通知当前状态
		listener(connectionState);
	},

	// 移除连接状态监听器
	removeConnectionListener(listener) {
		connectionListeners = connectionListeners.filter(l => l !== listener);
	},

	// 通知所有连接状态监听器
	notifyConnectionListeners() {
		connectionListeners.forEach(listener => {
			try {
				listener(connectionState);
			} catch (e) {
				console.error('连接监听器执行错误:', e);
			}
		});
	},

	// 更新连接状态
	updateConnectionState(newState) {
		if (connectionState !== newState) {
			console.log(`连接状态变更: ${connectionState} -> ${newState}`);
			connectionState = newState;
		}
	},

	// 订阅消息
	subscribe(destination, callback, headers = {}) {
		console.log("sdasdasdada:  "+destination)
		if (!stompClient) {
			console.error('STOMP客户端未初始化');
			return null;
		}

		if (!this.isConnected()) {
			console.error('STOMP客户端未连接，无法订阅');
			return null;
		}

		console.log(`正在订阅目的地: ${destination}`);
		const subscription = stompClient.subscribe(destination, (message) => {
			console.info(`收到消息 from ${destination}:`, message);
			try {
				const parsedBody = JSON.parse(message.body);
				callback(parsedBody);
			} catch (e) {
				console.error('消息解析错误:', e);
				callback(message.body, message.headers);
			}
		}, headers);

		const subscriptionId = `sub-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
		subscriptions[subscriptionId] = {
			destination,
			subscription,
			callback
		};

		console.log(`订阅成功，ID: ${subscriptionId}`, {
			destination
		});
		return subscriptionId;
	},

	// 取消订阅
	unsubscribe(subscriptionId) {
		if (!subscriptions[subscriptionId]) {
			console.warn(`未找到订阅ID: ${subscriptionId}`);
			return;
		}

		const {
			destination,
			subscription
		} = subscriptions[subscriptionId];
		try {
			subscription.unsubscribe();
			delete subscriptions[subscriptionId];
			console.log(`取消订阅成功，ID: ${subscriptionId}`, {
				destination
			});
		} catch (e) {
			console.error(`取消订阅失败，ID: ${subscriptionId}`, e);
		}
	},

	// 发送消息
	send(destination, body, headers = {}) {
		if (!this.isConnected()) {
			console.error('STOMP客户端未连接，无法发送消息');
			return false;
		}

		try {
			const messageBody = typeof body === 'string' ? body : JSON.stringify(body);
			console.log(`发送消息到 ${destination}`, {
				body: messageBody,
				headers
			});

			// 确保 body 是一个对象，并且包含所有必要字段
			const payload = typeof body === 'object' ? body : JSON.parse(messageBody);

			// 确保发送者ID和接收者ID存在
			if (!payload.senderId || !payload.receiverId) {
				console.error('发送者ID或接收者ID缺失');
				return false;
			}

			stompClient.publish({
				destination,
				body: JSON.stringify(payload) // 确保发送的是字符串化的JSON
			});

			return true;
		} catch (e) {
			console.error('消息发送失败:', e);
			return false;
		}
	},

	// 断开连接
	disconnect() {
		if (!stompClient) {
			console.warn('STOMP客户端未初始化，无需断开');
			return;
		}

		console.log('正在断开STOMP连接...');
		try {
			// 取消所有订阅
			Object.keys(subscriptions).forEach(subId => {
				this.unsubscribe(subId);
			});

			// 断开连接
			stompClient.deactivate().then(() => {
				console.log('STOMP连接已断开');
				stompClient = null;
				this.updateConnectionState(ConnectionState.DISCONNECTED);
				this.notifyConnectionListeners();
			});
		} catch (e) {
			console.error('断开连接时出错:', e);
		}
	},

	// 检查连接状态
	isConnected() {
		return stompClient && stompClient.connected;
	},

	// 获取当前连接状态
	getConnectionState() {
		return connectionState;
	},

	// 获取所有活跃订阅
	getSubscriptions() {
		return Object.keys(subscriptions).map(subId => ({
			id: subId,
			destination: subscriptions[subId].destination
		}));
	}
};